/**
 * @file models/standard.js
 * @author
 */
import { routerRedux } from 'dva/router';
import api from '../api';
import moment from 'moment'

//默认上个月
const lastMonth=moment().subtract(1, 'month')

export default {
	namespace: 'standard',
	state: {
		//产品ID
		portId:'',
		//产品列表
		portList:[],
		timeSlot:'0',
		quarter:null,
		//开始时间
		beginDate:`${lastMonth.format('YYYYMM')}01`,
		//结束时间
		endDate:moment(`${lastMonth.format('YYYYMM')}01`).add(1, 'month').subtract(1, 'day').format('YYYYMMDD'),
		//情景ID
		sceneId:'',
		//情景列表
		sceneList:[],
		//基准ID
		benchId:'',
		//报表类型
		fundStyle:'',
		showReport:false,
		pdtName:'',//产品名称
	},
	subscriptions : {
		setup({dispatch, history}) {
			history.listen(({ pathname, query }) => {
				// 没有参数时，向后端请求数据，并且改变query
				if( pathname === '/investmentSummary/investReport' ){
					dispatch({type: 'whetherRequest',payload:query,pathname})
				}
			})
		}
	},
	effects : {

		* whetherRequest({
				payload,pathname
			}, { put,select}) {



				const state=yield select(state=>state.standard)

				if(!(state.portList&&state.portList.length)){
					yield put({
						type:'queryPort',
						payload
					})
				}


				if(payload.portId&&payload.beginDate&&payload.endDate){
					if(!(payload.portId===state.portId&&payload.beginDate===state.beginDate&&payload.endDate===state.endDate)){
						yield put({
							type:'queryReportParams',
							payload
						})
					}
				}


				yield put({
					type:'setState',
					payload:{
						...payload,
						showReport:payload.beginDate&&payload.benchId&&payload.endDate&&payload.fundStyle&&payload.portId&&payload.sceneId?true:false,
					}
				})
		},

		* queryPort({payload}, {call, put,select}){
			const state=yield select(state=>state.standard)
			const portList = (yield call(api.report.portList, {
				orgCode:'ZCTGB'
			})).data.map(item=>({
				key:String(item.port_id),
				label:item.port_name,
			}))
			yield put({
				type:'setState',
				payload:{
					portList
				}
			})

		},
		* queryReportParams({payload}, {call, put,select}){

			const state=yield select(state=>state.standard)
			yield put({
				type:'setState',
				payload
			})
			const reportParams = (yield call(api.report.getReportParams, payload)).data
			const sceneList=reportParams.simulations&&reportParams.simulations.length&&reportParams.simulations.map(item=>({
				key:String(item.simulation_id),
				label:item.simulation_name,
			}))||[]

			yield put({
				type:'setState',
				payload:{
					sceneList,
					sceneId:state.sceneId||'0',
					benchId:reportParams.bench_id||state.benchId,
					fundStyle:reportParams.fund_style||state.fundStyle,
				}
			})
		},
		* changeRouter({payload}, {put}){
			// console.log('changeRouter',payload)
			
			yield put(routerRedux.push(payload))
		}

	},
	reducers : {
		setState(state, {payload}) {
			return {
				...state,
				...payload
			}
		},
		clearState(state) {
			const {
				...other
			}=state
      return{
				...other
			}
    },
	}
};
